package controller;

import java.io.IOException;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Calendar;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import model.BookingIO;
import model.Flight;
import model.Users;

/**
 * Servlet implementation class UpdateHistory
 */
public class UpdateHistory extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public UpdateHistory() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}


	/**
	 * The doPost method gets cart and adds all of those flights to a booking
	 * history for the current user. Then the cart is cleared out
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	@SuppressWarnings("unchecked")
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//Get session object
		HttpSession session = request.getSession();
		ArrayList<Flight> cart = (ArrayList<Flight>) session.getAttribute("shoppingCart");
		String userName = (String) session.getAttribute("user");		
		
		Users users = new Users();
		
		boolean added = true;
		BookingIO bookingIO = new BookingIO();
		int userID = users.getUserID(userName);

		//Add each flight to the booking history
		for(int i=0; i<cart.size(); i++){
			Flight flight = cart.get(i);
			Calendar calendar = Calendar.getInstance();
			Timestamp currentTimestamp = new java.sql.Timestamp(calendar.getTime().getTime());
			added = added && bookingIO.addBooking(currentTimestamp, flight.getId(), flight.getSeats(),
					userID, (flight.getCost()*flight.getSeats()), flight.getSelectedClass());
		}
		
		//Clear out cart
		cart = new ArrayList<Flight>();
		session.removeAttribute("shoppingCart");
		
		//Return message
		if(added){
			response.getWriter().write("added");
		} else {
			response.getWriter().write("notAdded");
		}

	}

}
